package com.yangyang.rpc.core.netcom.netty.client;

import com.yangyang.rpc.core.netcom.common.bean.RpcCallbackFuture;
import com.yangyang.rpc.core.netcom.common.bean.RpcRequest;
import com.yangyang.rpc.core.netcom.common.bean.RpcResponse;
import com.yangyang.rpc.core.netcom.common.client.AbstractClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by chenshunyang on 2016/11/19.
 */
public class NettyClient extends AbstractClient{
    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);


    @Override
    public RpcResponse send(RpcRequest request) throws Exception {

        NettyClientPoolProxy clientPoolProxy = null;
        GenericObjectPool<NettyClientPoolProxy> clientPool =  NettyClientPool.getPool(serverAddress,serializer,request.getClassName());;
        try {
            // future init
            RpcCallbackFuture future = new RpcCallbackFuture(request);
            RpcCallbackFuture.futurePool.put(request.getRequestId(), future);

            // rpc invoke
            clientPoolProxy = clientPool.borrowObject();
            clientPoolProxy.send(request);

            // future get
            return future.get(timeoutMillis);

        } catch (Exception e) {
            logger.error("", e);
            throw e;
        } finally {
            RpcCallbackFuture.futurePool.remove(request.getRequestId());
            clientPool.returnObject(clientPoolProxy);
        }
    }
}
